package com.sky.controller;


import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.entity.User;
import com.sky.entity.result.Result;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.service.UserService;
import com.sky.utils.DigitUtils;
import com.sky.utils.JwtUtil;
import com.sky.utils.ThreadLocalUtil;
import io.jsonwebtoken.Claims;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 用户接口地址
 */

@Slf4j
@Validated
@RestController
@RequestMapping("/admin")
@Tag(name = "用户接口", description = "用户注册及登录接口")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /* *
     * 用户注册接口
     * @param username
     * @param password
     * */
    @PostMapping("/register")
    @Operation(summary = "用户注册", description = "用户注册接口")
    public Result<String> register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        User user = userService.findByUsername(username);
        if (user == null) {
            // 没有占用用户名，可以注册
            userService.register(username, password);
            return Result.success(MessageConstant.REGISTER_SUCCESS);
        } else {
            // 用户名已占用
            return Result.error(MessageConstant.ALREADY_EXIST);
        }
    }

    /* *
     * 用户登录接口
     * @param username
     * @param password
     * */
    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户登录接口")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        User user = userService.findByUsername(username);
        // 生成jwt token
        String loginPassword = DigitUtils.md5DigestAsHex(password);
        if (loginPassword.equals(user.getPassword())) {
            Map<String, Object> claims = new HashMap<>();
            claims.put(JwtClaimsConstant.USER_ID, user.getId());
            claims.put(JwtClaimsConstant.USERNAME, user.getUsername());
            String token = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), claims);
            // 存入redis,时间为2小时;
            //stringRedisTemplate.opsForValue().set(token, token, JwtClaimsConstant.HOURS, TimeUnit.HOURS);
            // 测试解析token
            //Claims parsedClaims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            //log.info("Parsed Claims: {}", parsedClaims);
            log.info(MessageConstant.LOGIN_SUCCESS);
            return Result.success(token);
        } else {
            return Result.error(MessageConstant.PASSWORD_ERROR);
        }

    }

    @GetMapping("/userInfo")
    @Operation(summary = "获取用户信息", description = "获取用户信息接口")
    public Result<User> userInfo() {
        //Map<String, Object> claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
        Claims claims = ThreadLocalUtil.get();
        log.info("Claims: {}", claims);
        String username = (String) claims.get(JwtClaimsConstant.USERNAME);
        return Result.success(userService.findByUsername(username));
    }

    // 更新用户信息
    @PutMapping("/update")
    @Operation(summary = "更新用户信息", description = "更新用户信息接口")
    public Result<String> update(@RequestBody @Validated User user) {
        // 调用UserMapper的update方法，更新用户信息
        userService.update(user);
        // 返回操作成功的消息
        return Result.success(MessageConstant.OPERATION_SUCCESS);
    }

    // 更新用户密码
    @PatchMapping("/updatePassword")
    @Operation(summary = "更新用户密码", description = "更新用户密码接口")
    public Result updatePassword(@RequestBody Map<String, String> params, @RequestHeader("token") String token) {
        // 校验参数
        String oldPassword = params.get("oldPassword");
        String newPassword = params.get("newPassword");
        String confirmPassword = params.get("confirmPassword");
        // 校验参数是否为空值
        if (!StringUtils.hasLength(oldPassword) || !StringUtils.hasLength(newPassword) || !StringUtils.hasLength(confirmPassword)) {
            return Result.error(MessageConstant.PARAMETER_ERROR);
        }
        // 原密码是否正确
        Map<String, Object> claims = ThreadLocalUtil.get();
        String username = (String) claims.get(JwtClaimsConstant.USERNAME);
        User loginUser = userService.findByUsername(username);
        // 原密码是否正确
        if (!loginUser.getPassword().equals(DigitUtils.md5DigestAsHex(oldPassword))) {
            return Result.error(MessageConstant.PASSWORD_ERROR);
        }
        // 新密码是否与确认密码相同
        if (!newPassword.equals(confirmPassword)) {
            return Result.error(MessageConstant.PARAMETER_ERROR);
        }
        // 调用UserMapper的updatePassword方法，更新用户密码
        userService.updatePassword(newPassword);
        // 删除redis中的token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
        return Result.success(MessageConstant.OPERATION_SUCCESS);
    }
}


